<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    width="50%"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <div class="add-user">
      <BasicForm @register="registerForm">
        <template #remoteSearch="{ model, field }">
          <ApiSelect
            :api="getRoleList"
            showSearch
            placeholder="请选择角色"
            v-model:value="model[field]"
            :filterOption="false"
            labelField="roleName"
            showUploadIcon
            valueField="roleId"
            :params="searchParams"
            @search="debounceFn"
          />
        </template>
        <template #userUpload="{ model, field }">
          <HUpload
            v-model:value="model[field]"
            :max-size="18"
            :dragger="false"
            :title="getAvatarTitle"
            :accept="['jpg', 'png']"
            :show-file-name="false"
            @change="change"
          >
            <template #tips>
              <div class="tips">
                <span>支持JPG、PNG格式，单张图片不超过18M</span>
              </div>
            </template>
          </HUpload>
        </template>
      </BasicForm>
      <Divider plain @click="allowShow = !allowShow">
        <span class="allow-icon" :class="{ 'allow-down': !allowShow }">
          <UpOutlined /> {{ getAllowTitle }}</span
        >
      </Divider>
      <BasicForm @register="registerForms" v-show="allowShow" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { HUpload } from '/@/components/Upload';
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { ApiSelect } from '/@/components/Form/index';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema, accountFormSchemaAllow } from './account.data';
  import { Divider } from 'ant-design-vue';
  import { UpOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getDeptTreeByPage } from '/@/api/admin/dept';
  import { addUserApi, getUserInfoApi, updateUserApi, getRoleList } from '/@/api/admin/user';
  import { debounce } from 'lodash-es';
  import { isArray } from '/@/utils/is';

  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm, ApiSelect, Divider, UpOutlined, HUpload },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      let updateInfo = {};
      const getAvatarTitle = ref('上传图片');
      const allowShow = ref(true);
      const isUpdate = ref(true);
      const rowId = ref<Nullable<string | undefined>>(undefined);

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 12 },
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        // alwaysShowLines: 8,
        // showAdvancedButton: true,
        // showResetButton: false,
        // showSubmitButton: false,
        // autoAdvancedLine: 3,
        actionColOptions: {
          span: 23,
        },
      });

      const [
        registerForms,
        {
          setFieldsValue: setFieldsValueAllow,
          resetFields: resetFieldsAllow,
          validate: validateAllow,
        },
      ] = useForm({
        labelWidth: 100,
        baseColProps: { span: 12 },
        schemas: accountFormSchemaAllow,
        showActionButtonGroup: false,
        // alwaysShowLines: 8,
        // showAdvancedButton: true,
        // showResetButton: false,
        // showSubmitButton: false,
        // autoAdvancedLine: 3,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        resetFieldsAllow();
        setModalProps({ confirmLoading: false });

        isUpdate.value = !!data?.isUpdate;
        allowShow.value = !unref(isUpdate);
        // setProps({ showAdvancedButton: isUpdate.value });
        rowId.value = undefined;
        if (unref(isUpdate)) {
          rowId.value = data.record.userId;
          const res = await getUserInfoApi(rowId.value as string);
          updateInfo = res;
          const { roleList, deptList, postList } = res;
          if (roleList && roleList.length) {
            res.role = roleList.map((el) => el.roleId);
          }
          if (deptList && deptList.length) {
            res.dept = deptList.map((el) => el.deptId);
          }
          if (postList && postList.length) {
            res.post = postList.map((el) => el.postId);
          }
          res.avatar && (res.avatar = [{ url: res.avatar, status: 'done' }]);

          setFieldsValue({
            ...res,
          });
          setFieldsValueAllow({ ...res });
        }

        const treeData = await getDeptTreeByPage();
        updateSchema([
          {
            field: 'deptId',
            componentProps: { treeData },
          },
          {
            field: 'dept',
            componentProps: { treeData },
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增用户' : '编辑用户'));
      const getAllowTitle = computed(() => (unref(allowShow) ? '以下是展开信息' : '展开更多信息'));

      async function handleSubmit() {
        try {
          const values = await validate();
          const valuesAllow = await validateAllow();
          if (isArray(values.avatar)) {
            values.avatar = values.avatar.map((i) => i.url).toString();
          }
          setModalProps({ confirmLoading: true });
          values.userId = rowId.value;
          const params = Object.assign(updateInfo, values, valuesAllow);
          const apiFn = unref(isUpdate) ? updateUserApi : addUserApi;
          await apiFn(params);
          createMessage.success('操作成功');

          closeModal();
          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const keyword = ref<string>('');
      const searchParams = computed<Recordable>(() => {
        return { roleName: unref(keyword) };
      });

      const debounceFn = debounce(function onSearch(value: string) {
        keyword.value = value;
      }, 800);

      const change = (file) => {
        if (file.length) {
          getAvatarTitle.value = '重新上传';
        } else {
          getAvatarTitle.value = '上传图片';
        }
      };

      return {
        registerModal,
        registerForm,
        registerForms,
        getTitle,
        handleSubmit,
        searchParams,
        debounceFn,
        getRoleList,
        allowShow,
        getAllowTitle,
        getAvatarTitle,
        change,
      };
    },
  });
</script>

<style scoped lang="less">
  .add-user {
    width: calc(100% - 20px);
    margin: auto;
  }

  :deep(.ant-picker.ant-picker-default) {
    width: 100%;
  }

  :deep(.allow-icon) {
    color: #999999;
    font-size: 14px;
    cursor: pointer;
  }

  :deep(.allow-down) {
    color: #2b63a1;

    span.anticon:not(.app-iconify) {
      transform: rotate(180deg);
    }
  }

  :deep(.tips) {
    display: table;
    margin-top: 25px;

    span {
      display: table-cell;
      vertical-align: bottom;
      color: #999999;
      font-size: 14px;
    }
  }
</style>
